package com.flyfish.ddns.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * properties 文件读取
 * 
 * @author tanchong
 *
 */
public final class PropertiesUtil {

	// 指定配置文件地址//resource目录下:
	static Properties prop = new Properties();
	static {
		// 初始化数据
		init();
		File directory = new File("");// 参数为空
		String courseFile;
		try {
			courseFile = directory.getCanonicalPath();
			String path = courseFile + File.separatorChar + "ddns.properties";
			InputStream is = new FileInputStream(new File(path));
			// InputStream is =
			// PropertiesUtil.class.getClassLoader().getResourceAsStream("ddns.properties");
			System.out.println("读取配置文件：" + courseFile);
			prop.load(is);
			System.out.println("成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化文件数据，如果数据不存在，则进行创建文件
	 */
	public static void init() {
		File directory = new File("");// 参数为空
		String courseFile;
		try {
			courseFile = directory.getCanonicalPath();
			String path = courseFile + File.separatorChar + "ddns.properties";
			System.out.println("开始DDNS检查，获取配置信息。文件路径：" + path);
			File file = new File(path);
			// 判定文件是否存在
			if (!file.exists()) {
				System.out.println("文件不存在，进行生成模板");
				StringBuilder fileContent = new StringBuilder();
				// 生成模板内容
				fileContent.append("AccessKeyID=aaaaaaaaa\r\n");
				fileContent.append("AccessKeySecret=bbbbb\r\n");
				fileContent.append("DomainName=xxxx.com\r\n");
				fileContent.append("logPath=/data/soft/logs/log.txt\r\n");
				fileContent.append("waitTime=300\r\n");
				// 生成文件
				FileUtils.createFile(courseFile + File.separatorChar, "ddns.properties", fileContent.toString());
			}
			System.out.println(courseFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getProperty(String key) {
		return prop.getProperty(key);
	}

	public static String getProperty(String key, String value) {
		return getProperty(key, value);
	}

	public static void main(String[] args) {
		System.out.println(PropertiesUtil.getProperty("AccessKeyID"));
	}
}
